# 解析刷写文件
# 解析s19文件，返回一个字典，包含start_address, data_length, parsed_data（字节数组格式）, crc32
# 解析hex文件，返回一个字典，包含start_address, data_length, parsed_data（字节数组格式）, crc32
# 通用操作，所以拆分出来封装成一个函数，方便调用

import binascii
from myLog import logger

# 解析s19文件
def parse_s19_file(file_path):
    hex_data = {
        "start_address": 0,
        "data_length": 0,
        "parsed_data": bytearray(),
        "crc32": 0
    }
    data_line = 0
    data_num = 0
    last_address = 0
    last_length = 0
    data_flag = 0

    with open(file_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            # logger.info ("*line: {}".format(line))
            if line[0] == 'S':
                record_type = line[1]
                # logger.info("*record_type: S{}".format(record_type))
                byte_count = int(line[2:4], 16)
                # logger.info("*byte_count: {}".format(byte_count))
                address = int(line[4:12], 16) if record_type in ('1', '2', '3') else 0
                # logger.info("*address: {}".format(address))

                if record_type in ('1', '2', '3'):
                    data_flag = 1
                    data_start_index = 10 if record_type == '1' else (12 if record_type == '2' else 14)
                    data_end_index = data_start_index + 2 * (byte_count - (data_start_index - 4) // 2)
                    data = bytes.fromhex(line[data_start_index:data_end_index])
                else:
                    data_flag = 0
                    data = b''

                if data_flag:
                    data_line += 1
                    if data_line == 1:
                        hex_data["start_address"] = address
                        # logger.info("start_address: {}".format(hex_data["start_address"]))
                    else:
                        if address!= (last_address + last_length):
                            logger.error("存在不连续的数据块，可能需要进一步处理")
                            hex_data["data_length"] = 0
                            return hex_data

                    last_length = len(data)
                    hex_data["data_length"] += last_length
                    hex_data["parsed_data"].extend(data)
                    if hex_data["start_address"] == 0:
                        hex_data["start_address"] = address
                    last_address = address

    logger.info("start_address: {}".format(hex_data["start_address"]))
    logger.info("data_length: {}".format(hex_data["data_length"]))

    hex_data["crc32"] = binascii.crc32(hex_data["parsed_data"])
    # logger.info("hex_data: {}".format(hex_data))
    return hex_data



# 解析hex文件
def parse_hex_file(file_path):
    hex_data = {
        "start_address": 0,
        "data_length": 0,
        "parsed_data": bytearray(),
        "crc32": 0
    }
    data_line = 0
    data_num = 0
    first_address = 0

    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            for line in lines:
                if line[0] == ':':
                    byte_count = int(line[1:3], 16)
                    address = int(line[3:7], 16)
                    record_type = int(line[7:9], 16)

                    if record_type == 0x04:  # 扩展线性地址记录
                        block_start_address = int(line[9:13], 16)
                        hex_data["start_address"] = block_start_address << 16
                        data_line = 0

                    elif record_type == 0x00:  # 数据记录
                        data_line += 1
                        if data_line == 1:
                            hex_data["start_address"] += address
                            first_address = address
                        hex_data["data_length"] += byte_count
                        hex_data["parsed_data"].extend(bytes.fromhex(line[9:9 + 2 * byte_count]))
                        if hex_data["start_address"] == 0:
                            hex_data["start_address"] = address

                    elif record_type == 0x01:  # 文件结束记录
                        break
    except FileNotFoundError:
        logger.error(f"无法打开文件: {file_path}")

    hex_data["crc32"] = binascii.crc32(hex_data["parsed_data"])
    return hex_data